package com.micro.magupe.auth.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import com.micro.magupe.auth.security.AuthJwtAccessTokenConverter;
import com.micro.magupe.auth.service.MicroUserDetailsService;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

	@Autowired
    private AuthenticationManager authenticationManager;

	@Autowired
	private MicroUserDetailsService userDetailsService;
	
    @Autowired
    private DataSource dataSource;

    @Bean
    public WebResponseExceptionTranslator webResponseExceptionTranslator(){
    	return new DefaultWebResponseExceptionTranslator();
    }
    
    @Bean
    public JdbcTokenStore jdbcTokenStore(){
    	return new JdbcTokenStore(dataSource);
    }
	
    @Bean
    public ClientDetailsService clientDetails() {
        return new JdbcClientDetailsService(dataSource);
    }
	
    /**
     * 注意，自定义TokenServices的时候，需要设置@Primary，否则报错
     */
    @Primary
    @Bean
    public DefaultTokenServices defaultTokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(jdbcTokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setClientDetailsService(clientDetails());
        tokenServices.setAccessTokenValiditySeconds(60*60*12); // token有效期自定义设置，默认12小时
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);//默认30天，这里修改
        tokenServices.setTokenEnhancer(accessTokenConverter());
        return tokenServices;
    }
    
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
    	AuthJwtAccessTokenConverter converter = new AuthJwtAccessTokenConverter();
        converter.setSigningKey("880204");
        return converter;
    }
    
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
        	.tokenStore(jdbcTokenStore())
        	.tokenServices(defaultTokenServices())
        	.accessTokenConverter(accessTokenConverter())
        	.userDetailsService(userDetailsService)
        	.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
        	.authenticationManager(authenticationManager)
        	.exceptionTranslator(webResponseExceptionTranslator());
    }
    
	@Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    	security
    		.tokenKeyAccess("permitAll()")
    		.checkTokenAccess("isAuthenticated()")
    		.allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    	clients.withClientDetails(clientDetails());
    }
    
}
